package cz.mendelu.swi2.catalogOfRobots;

//this if from example
import java.util.ArrayList;

import javax.validation.Valid;

import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoaderListener;

import cz.mendelu.swi2.form.Registration;




@Controller
public class RobotController {
	private RobotRepository repository = RobotRepository.getInstance();
	
	@RequestMapping("/robot/add")
	public ModelAndView add() {
		ModelAndView view = new ModelAndView("catalogOfRobots/robotForm");
		if(!repository.checkRole()){
			view.addObject("message","K akci nemate opravneni.");
			view.addObject("error","1");
		}else{
			view.addObject("error","0");
		}
		view.addObject("robot", new Robot());
		return view;
	}
	
	@RequestMapping(value = "/robot/save", method = RequestMethod.POST)
	public String save(@Valid Robot robot, BindingResult result) {
		if (robot.getId() == 0) {
			robot.setId(repository.getRobots().size() + 1);
		}
		
		repository.addRobot(robot);
		return "redirect:/forms/robot/list";
	}
	
	@RequestMapping("/robot/detail")
	public ModelAndView detail(@Valid Robot robot, BindingResult result) {
		Robot detail = repository.getRobot(robot.getId());
	
		return new ModelAndView("catalogOfRobots/robotDetail", "robot", detail);
	}
	@RequestMapping("/robot/list")
	public ModelAndView list() {
		ModelAndView view = new ModelAndView("catalogOfRobots/robotList");
		if(!repository.checkRole()){
			view.addObject("error", "1");
		}else{
			view.addObject("error", "0");
		}
		view.addObject("robots", repository.getRobots() );
		return view;
	}
	   
	@RequestMapping(value = "/robot/edit", method = RequestMethod.GET)
	public ModelAndView edit(@Valid Robot robot, BindingResult result) {
		ModelAndView view = new ModelAndView("catalogOfRobots/robotForm");
		if(!repository.checkRole()){
			view.addObject("message","K akci nemate opravneni.");
			view.addObject("error","1");
		}else{
			view.addObject("error","0");
		}
		view.addObject("robot", repository.getRobot(robot.getId()));
		return view;
	}

	
	
	
}
